import axios from 'axios'
import Router from '@/router'
import Qs from 'qs'

class HttpRequest {
  constructor () {
    this.baseUrl = 'http://yapi.demo.qunar.com/mock/3566'
    this.queue = {}
  }

  getInsideConfig () {
    const config = {
      baseURL: this.baseUrl
      // headers: {
      //   timeout: 30000
      // }

    }
    return config
  }

  destroy (url) {
    delete this.queue[url]
    if (!Object.keys(this.queue).length) {
      // Spin.hide()
    }
  }

  interceptors (instance, url) {
    // 请求拦截
    instance.interceptors.request.use(config => {
      // 添加全局的loading...
      if (config.method == 'post') {
        config.transformRequest = [
          function (data) {
            // 对 data 进行任意转换处理
            return Qs.stringify(data)
          }
        ]
      }
      return config
    }, error => {
      return Promise.reject(error)
    })
    // 响应拦截
    instance.interceptors.response.use(
      res => {
        this.destroy(url)
        const {data} = res
        return data
      },
      err => {
        const {data} = err.response
        if (data.code == 401) {
          // store.commit('changeUser', null)
          Router.push('/')
        }
      }
    )
  }

  request (options) {
    // options.url = checkUrl(options.url)
    const instance = axios.create()
    options = Object.assign(this.getInsideConfig(), options)
    this.interceptors(instance, options.url)
    return instance(options)
  }
}

const Axios = new HttpRequest()

export default Axios
